/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package shipwright.water;

import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.PhysicsTickListener;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.system.Timer;
import jme3test.water.WaterHeightGenerator;
import shipwright.parts.BoatBlock;
import shipwright.parts.BoatBlockBody;

/**
 *
 * @author root
 */
public class BuoyancyControl implements PhysicsTickListener {
    
    private Node boat;
    private WaterHeightGenerator waterHeightGenerator;
    private Timer timer;

    public BuoyancyControl(WaterHeightGenerator whg, Timer timer, Node boat) {
        this.boat = boat;
        this.waterHeightGenerator = whg;
        this.timer = timer;

    }

    public void prePhysicsTick(PhysicsSpace space, float tpf) {

        
        for (Spatial s : boat.getChildren()) {
            BoatBlockBody boatPhys = s.getControl(BoatBlockBody.class);
            Vector3f phyLoc = boatPhys.getPhysicsLocation();
            float waterHeight = waterHeightGenerator.getHeight(phyLoc.x, phyLoc.z, timer.getTimeInSeconds());
            if (phyLoc.y < waterHeight) {//TODO: fix point
                double submerged = waterHeight - phyLoc.y;
                if (submerged > 0.0) {
                    boatPhys.setDamping(.95f, .95f);
                }
                if (submerged > BoatBlock.y) {
                    submerged = BoatBlock.y;
                }

                double force = BoatBlock.x * BoatBlock.z * submerged * 9.81;
                boatPhys.applyForce(new Vector3f(0, (float) force, 0), new Vector3f(0,0,0));
                
                if(boatPhys.getPrevLoc() != null){
                    Vector3f waveForce = phyLoc.subtract(boatPhys.getPrevLoc()).mult(2f);
                    boatPhys.applyCentralForce(waveForce);
                }
            }
            else{
                boatPhys.setDamping(0, 0);
            }
            boatPhys.setPrevLoc(phyLoc);
        }
       

    }

    public void physicsTick(PhysicsSpace space, float tpf) {
        // poll game state ...
    }
}
